package org.example.springboot.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域过滤器
 * /* 代表所有资源 过滤所有servlet
 */
@WebFilter("/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //过滤方法 请求和响应
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        //设置响应头 Access-Control-Allow-Origin 允许的域名为 *
        response.setHeader("Access-Control-Allow-Origin", "*");
        //允许所有方法
        response.setHeader("Access-Control-Allow-Methods", "*");
        //允许所有的请求头
        response.setHeader("Access-Control-Allow-Headers", "*");
        //放行请求和响应
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
